package cn.funeralobjects.upms.controller;

import cn.funeralobjects.common.service.CommonCloudService;
import cn.funeralobjects.common.service.CommonTreeCrudService;
import cn.funeralobjects.common.service.exception.DataInvalidException;
import cn.funeralobjects.common.web.controller.CommonCloudController;
import cn.funeralobjects.common.web.controller.CommonTreeCrudController;
import cn.funeralobjects.common.web.controller.converter.ModelMapper;
import cn.funeralobjects.upm.web.model.MGroup;
import cn.funeralobjects.upm.web.model.VGroup;
import cn.funeralobjects.upms.api.GroupApi;
import cn.funeralobjects.upms.controller.converter.GroupMapper;
import cn.funeralobjects.upms.entity.EGroup;
import cn.funeralobjects.upms.model.Group;
import cn.funeralobjects.upms.service.GroupService;
import cn.funeralobjects.util.ReactorUtils;
import cn.funeralobjects.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * Group外部访问接口
 *
 * @author FuneralObjects
 * Create date: 2020/4/28 2:11 PM
 */
@RestController
@RequestMapping(name = "group", path = "/group")
public class GroupController implements GroupApi, CommonCloudController<VGroup, EGroup, Integer>, CommonTreeCrudController<VGroup, MGroup, Group, EGroup, Integer> {

    @Resource
    private GroupService groupService;

    @Resource
    private GroupMapper groupMapper;

    @PostMapping("/{id}/tag")
    @Override
    public Mono<Void> addGroupTag(@PathVariable Integer id, @RequestParam String tag) {
        return Mono.just(id)
                .filter(groupService::isValid)
                .map(i -> {
                    if (StringUtils.hasLength(tag)) {
                        return i;
                    }
                    throw new DataInvalidException("The arg[tag] cannot be empty!", groupService.createDataCode("tag", tag));
                })
                .flatMap(ReactorUtils.thenEmpty(i -> groupService.addGroupTag(i, tag)));
    }

    @DeleteMapping("/{id}/tag/{tag}")
    @Override
    public Mono<Void> removeGroupTag(@PathVariable Integer id, @PathVariable String tag) {
        return Mono.just(id)
                .filter(groupService::isValid)
                .filter(i -> StringUtils.hasLength(tag))
                .flatMap(ReactorUtils.thenEmpty(i -> groupService.removeGroupTag(i, tag)));
    }


    @Override
    public CommonCloudService<EGroup, Integer> commonCloudEntityService() {
        return groupService;
    }


    @Override
    public ModelMapper<MGroup, Group, EGroup, VGroup> modelMapper() {
        return groupMapper;
    }

    @Override
    public CommonTreeCrudService<Group, EGroup, Integer> commonTreeCrudService() {
        return groupService;
    }
}
